<template>
  <div class="app-container">
    <!-- 搜索和操作区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input v-model="queryParams.samplingPointName" placeholder="搜索采样点名称" clearable @clear="handleSearch"
            @keyup.enter="handleSearch">
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 采样点表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog" icon="Plus">新增采样点</el-button>

      <el-table class="mt-2" :data="samplingPointList" border v-loading="loading" :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column prop="samplingPointName" label="采样点名称" width="180" />
        <el-table-column prop="samplingPointLocation" label="位置描述" />
        <el-table-column label="经纬度" width="220">
          <template #default="{ row }">
            {{ row.latitude ? row.latitude.toFixed(6) : '-' }}, {{ row.longitude ? row.longitude.toFixed(6) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" :close-on-click-modal="false">
      <el-form :model="currentPoint" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="采样点名称" prop="samplingPointName">
          <el-input v-model="currentPoint.samplingPointName" placeholder="如沉淀池出水口采样点" />
        </el-form-item>
        <el-form-item label="位置描述" prop="samplingPointLocation">
          <el-input v-model="currentPoint.samplingPointLocation" type="textarea" :rows="2"
            placeholder="详细描述采样点在水厂内的具体方位" />
        </el-form-item>
        <el-form-item label="纬度" prop="latitude">
          <el-input-number v-model="currentPoint.latitude" :min="-90" :max="90" :precision="6" :step="0.000001"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="经度" prop="longitude">
          <el-input-number v-model="currentPoint.longitude" :min="-180" :max="180" :precision="6" :step="0.000001"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="currentPoint.remark" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSamplingPointList,
  getSamplingPointDetail,
  addSamplingPoint,
  updateSamplingPoint,
  deleteSamplingPoint
} from '@/api/prod_operate/sys_setting/water/sampling_cfg'

// 加载状态
const loading = ref(false)

// 采样点列表数据
const samplingPointList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  samplingPointName: undefined
})

// 当前操作的点
const currentPoint = reactive({
  samplingPointId: '',
  samplingPointName: '',
  samplingPointLocation: '',
  latitude: undefined,
  longitude: undefined,
  remark: ''
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新增采样点')
const formRef = ref(null)

// 表单验证规则
const rules = reactive({
  samplingPointName: [
    { required: true, message: '请输入采样点名称', trigger: 'blur' }
  ],
  samplingPointLocation: [
    { required: true, message: '请输入位置描述', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    await fetchSamplingPointList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取采样点列表
const fetchSamplingPointList = async () => {
  try {
    loading.value = true
    const res = await getSamplingPointList(queryParams)
    samplingPointList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取采样点列表失败:', error)
    ElMessage.error('获取采样点列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  queryParams.pageNum = 1
  fetchSamplingPointList()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchSamplingPointList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchSamplingPointList()
}

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增采样点'
  resetCurrentPoint()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = async (row) => {
  try {
    loading.value = true
    const res = await getSamplingPointDetail(row.samplingPointId)
    Object.assign(currentPoint, res.data)
    dialogTitle.value = '编辑采样点'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取采样点详情失败:', error)
    ElMessage.error('获取采样点详情失败')
  } finally {
    loading.value = false
  }
}

// 重置当前点
const resetCurrentPoint = () => {
  currentPoint.samplingPointId = ''
  currentPoint.samplingPointName = ''
  currentPoint.samplingPointLocation = ''
  currentPoint.latitude = undefined
  currentPoint.longitude = undefined
  currentPoint.remark = ''
}

// 确认保存
const confirmSave = async () => {
  try {
    await formRef.value.validate()

    if (dialogTitle.value === '新增采样点') {
      await addSamplingPoint(currentPoint)
      ElMessage.success('新增采样点成功')
    } else {
      await updateSamplingPoint(currentPoint)
      ElMessage.success('修改采样点成功')
    }

    dialogVisible.value = false
    fetchSamplingPointList()
  } catch (error) {
    console.error('保存采样点失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除采样点 ${row.samplingPointName} 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteSamplingPoint(row.samplingPointId)
      ElMessage.success('删除成功')
      fetchSamplingPointList()
    } catch (error) {
      console.error('删除采样点失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-input-number {
  width: 100%;
}
</style>